import json
from openai import OpenAI

# 设置OpenAI API客户端
client = OpenAI(
    base_url="https://api.gptsapi.net/v1",
    api_key="sk-kghaf948e5e3bc901fdb866fa5f1ffe18d19d9961a8N5pAg"
)

# 从文件加载数据
with open('processed_test.json', 'r', encoding='utf-8') as file:
    case_data = json.load(file)


# 定义调用GPT-4 API进行案件相似度计算的函数
def calculate_similarity(case_a, case_b, case_c):
    try:
        response = client.chat.completions.create(
            model="gpt-4o",
            messages=[
                {"role": "system",
                 "content": "你是一个法律文本分析助手，任务是比较三个法律案件文本的相似度，并提供具体的分析和评分。"},
                {"role": "user", "content": f"请比较以下三个案件的文本，评估它们之间的相似度，并提供详细的比较说明。\n\n"
                                            f"案件A：\n{case_a}\n\n"
                                            f"案件B：\n{case_b}\n\n"
                                            f"案件C：\n{case_c}\n\n"
                                            "请按照以下格式提供相似度评分和说明：\n"
                                            "1. A与B的相似度评分：<评分，0-10>"
                                            "2. A与C的相似度评分：<评分，0-10>"
                                            "3. 综合分析：<详细的相似度比较说明，包括A与B、A与C的相似度评分以及哪个案件与A的相似度更高>"}
            ]
        )
        print(response)
        similarity_result = response.choices[0].message.content.strip()

        # 提取相似度评分和综合分析
        try:
            lines = similarity_result.split("\n")
            score_ab = float(lines[0].split("：")[1])
            score_ac = float(lines[1].split("：")[1])
            explanation = "\n".join(lines[2:])
        except:
            score_ab = None
            score_ac = None
            explanation = similarity_result

        return score_ab, score_ac, explanation
    except Exception as e:
        print(f"Error calculating similarity: {e}")
        return None, None, None


# 对每个案件对进行相似度计算
similarity_results = []
for case in case_data:
    case_a = case['A']
    case_b = case['B']
    case_c = case['C']

    # 计算 A 与 B 和 C 的相似度
    score_ab, score_ac, explanation = calculate_similarity(case_a, case_b, case_c)

    # 确定哪个案件与 A 最相似
    if score_ab is not None and score_ac is not None:
        if score_ab > score_ac:
            most_similar_case = 'B'
        else:
            most_similar_case = 'C'
    else:
        most_similar_case = 'Unknown'

    similarity_results.append({
        'case_id': case.get('case_id', 'Unknown'),
        'most_similar_case': most_similar_case,
        'similarity_score_ab': score_ab,
        'similarity_score_ac': score_ac,
        'similarity_explanation': explanation
    })

# 将相似度计算结果保存到JSON文件
with open('similarity_results.json', 'w', encoding='utf-8') as file:
    json.dump(similarity_results, file, ensure_ascii=False, indent=4)

print("相似案件匹配结果已保存到 'similarity_results.json' 文件中。")
